package com.chaoyer.cynet.service.impl;

import com.chaoyer.cynet.cache.GhostPostCache;
import com.chaoyer.cynet.cache.domain.GhostPost;
import com.chaoyer.cynet.common.exception.ValidateException;
import com.chaoyer.cynet.common.help.Assert;
import com.chaoyer.cynet.constant.Errors;
import com.chaoyer.cynet.dao.PostPvMapper;
import com.chaoyer.cynet.entity.PostPv;
import com.chaoyer.cynet.service.PostPvService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

/**
 * Created by apple.
 * Description:
 * Date: 2018-05-20
 * Time: 下午4:29
 */
@Service
public class PostPvServiceImpl implements PostPvService {


    @Resource
    private PostPvMapper postPvMapper;
    @Resource
    private GhostPostCache ghostPostCache;

    @Override
    public PostPv getPvByPostId(String postId) throws ValidateException {

        PostPv postPv = postPvMapper.findPvByPostId(postId);

        Assert.check(postPv, Errors.POST_NOT_EXIST);

        return postPv;
    }

    @Override
    public void addPvByPostId(String postId) {

        // 文章是否存在
        Optional<PostPv> postPv = Optional.ofNullable(postPvMapper.findPvByPostId(postId));
        if (postPv.isPresent()) {
            // 更新
            postPvMapper.updatePv(postId);
        } else {
            // 新增一条记录
            postPvMapper.addPv(postId);
        }
    }

    @Override
    public List<GhostPost> searchByPostName(String name) {

        List<GhostPost> ghostPosts = new ArrayList<>();
        HashMap<String, GhostPost> postCache = ghostPostCache.getPostCache();
        for (GhostPost ghostPost : postCache.values()) {
            if (ghostPost.getTitle().toLowerCase().contains(name.toLowerCase())) {
                ghostPosts.add(ghostPost);
            }
        }
        return ghostPosts;
    }
}
